package com.kyrioscraft.cloud.security.securitymoblie.repository;

import com.kyrioscraft.cloud.security.core.validate.code.ValidateCode;
import com.kyrioscraft.cloud.security.core.validate.code.ValidateCodeRepository;
import com.kyrioscraft.cloud.security.core.validate.code.ValidateCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @Author kyrioscraft
 * @Date 2019/1/8 15:54
 * @Description //TODO
 **/
@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {

    String REDIS_KEY_PREFIX = "REDIS_KEY_FOR_CODE_";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
        redisTemplate.opsForValue().set(getSessionKey(request,validateCodeType),code,30, TimeUnit.MINUTES);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        return (ValidateCode)redisTemplate.opsForValue().get(getSessionKey(request,validateCodeType));
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        redisTemplate.delete(getSessionKey(request,validateCodeType));
    }

    private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        return REDIS_KEY_PREFIX + validateCodeType.toString().toUpperCase();
    }
}
